package utils

import (
	"crypto/md5"
	"encoding/base64"
	"fmt"
	"strings"

	"golang.org/x/crypto/bcrypt"

	log "github.com/sirupsen/logrus"
)

func GenerateHtpasswd(username, pwd string) string {
	// 这里模仿htpasswd的行为，即在密码前加入用户名:
	toHash := username + ":" + pwd
	hash := md5.Sum([]byte(toHash))

	log.Trace(fmt.Sprintf("Generate Http passwd username %s,pwd %s", username, pwd))
	return strings.TrimSpace(base64.StdEncoding.EncodeToString(hash[:]))
}

func HashAndSalt(username, pwd string) string {
	hash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.MinCost)
	if err != nil {
		log.Println(err)
	}
	return string(hash)
}

// 验证密码
func ComparePasswords(hashedPwd string, plainPwd string) bool {
	byteHash := []byte(hashedPwd)
	err := bcrypt.CompareHashAndPassword(byteHash, []byte(plainPwd))
	if err != nil {
		log.Println(err)
		return false
	}
	return true
}
